<template>
    <section>
        <!--编辑表单start -->
        <el-form :model='editForm' label-width='220px' ref='editForm' class='add-form' :rules='editFormRules'>
            <el-row class='mt-10 row-padding'>
                <el-form-item label='优惠劵类型' class='mt-5'>
                    <el-select v-model='editForm.coupon_type' placeholder='请选择优惠劵类型'
                               class='input-middle'>
                        <el-option label='全场赠卷' value='1'></el-option>
                        <el-option label='注册赠卷' value='2'></el-option>
                        <el-option label='购物赠卷' value='3'></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label='优惠劵名称' class='mt-10' prop='coupon_title'>
                    <el-input v-model='editForm.coupon_title' class='input-middle'></el-input>
                </el-form-item>
                <el-form-item label='适用平台' class='mt-10'>
                    <el-select v-model='editForm.coupon_platform' placeholder='请选择优惠劵适用平台' class='input-middle'>
                        <el-option label='全平台' value='1'></el-option>
                        <el-option label='微信' value='2'></el-option>
                        <el-option label='PC' value='3'></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label='优惠是否可以同会员价同时使用' class='ml-20' prop='coupon_overlay_member'>
                    <el-radio-group v-model='editForm.coupon_overlay_member'>
                        <el-radio :label='1'>是</el-radio>
                        <el-radio :label='0'>否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label='发行量' prop='amount_type'>
                    <div>
                        <el-radio v-model='amount_type' :label='1'>库存量</el-radio>
                        <el-input-number v-model='editForm.coupon_amount' :min='0'></el-input-number>
                    </div>
                    <div style='margin-top: 10px'>
                        <el-radio v-model='amount_type' :label='2'>无限量</el-radio>
                    </div>
                </el-form-item>
                <el-form-item label='面额' prop='coupon_price'>
                    <el-input v-model='editForm.coupon_price' class='input-middle'> 元
                    </el-input>
                </el-form-item>
                <el-form-item label='每人限领' prop='coupon_limit'>
                    <el-input-number v-model='editForm.coupon_limit' :min='0'></el-input-number>
                    张
                </el-form-item>
                <el-form-item label='使用门槛' prop='coupon_threshold' class='mt-10'>
                    满
                    <el-input v-model='editForm.coupon_threshold' class='input-middle'></el-input>
                    元可用
                </el-form-item>
                <el-form-item label='有效期' prop='date_type'>
                    <div>
                        <el-radio v-model='date_type' :label='1'>固定日期</el-radio>
                        <el-date-picker
                                :disabled='date_type==2'
                                style='margin-left:44px'
                                v-model='date'
                                type='datetimerange'
                                range-separator='至'
                                start-placeholder='请选择结束日期'
                                end-placeholder='请选择开始日期'
                                value-format='yyyy-MM-dd HH:mm:ss'>
                        </el-date-picker>
                    </div>
                    <div style='margin-top: 10px'>
                        <el-radio v-model='date_type' :label='2'>使用时限</el-radio>
                        <el-input v-model='editForm.expire_days' style='width: 200px; margin-left:44px'
                                  :disabled='date_type==1'>
                        </el-input>
                        天
                    </div>
                </el-form-item>
                <el-form-item label='可使用商品' class='ml-20' prop='available_product'>
                    <el-radio-group v-model='editForm.available_product'>
                        <el-radio :label='1'>全部商品</el-radio>
                        <el-radio :label='0'>指定商品</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!--商品选择列表 start-->
                <el-form-item v-show='editForm.available_product===0'>
                    <el-col class='w-25 p-2 mr-3' style='border: 1px solid #ccc; height: 420px; overflow-y: auto;'>
                        <el-tree
                                class='filter-tree'
                                :data='Options'
                                :props='classifyProps'
                                :check-strictly='false'
                                ref='tree'
                                @check-change='getProduct'
                                @node-click='productView'
                                :show-checkbox='true'
                                :getCurrentKey='true'
                                v-loading='listLoading'
                                default-expand-all
                                :filter-node-method='filterNode'>
                        </el-tree>
                    </el-col>
                    <el-col id="tableCssOne" style='width: 25%; padding-left:10px; padding-right: 2px; padding-bottom: 10px; padding-top:50px; border: 1px solid #ccc; position: relative;'>
                        <el-input placeholder='请输入内容' v-model='searchName' class='input-with-select search'>
                            <el-button slot='append' @click='searchProductList' icon='el-icon-search'></el-button>
                        </el-input>
                        <el-table :data='productList' style='height: 358px; overflow-y:auto;' :row-class-name='tableRowClassName' v-loading='listLoading'>
                            <el-table-column prop='product_name'>
                            </el-table-column>
                            <el-table-column width='50'>
                                <template slot-scope='scope'>
                    <span class='color-blue pointer' style='text-align: right;'
                          @click='deleteProduct(scope.row.product_id)'>删除</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                    <el-col class="mx-2" style="width: 60px; margin-top: 140px;">
                        <el-button type="primary" @click="addToCoupon" > >></el-button>
                    </el-col>
                    <el-col id="tableCssTwo" class='p-2' style='width: 25%; border: 1px solid #ccc; position: relative;'>
                        <el-table :data='couponProductList' style='height: 418px; overflow-y: auto;' :row-class-name='tableRowClassName' v-loading='listLoading'>
                            <el-table-column prop='product_name'>
                            </el-table-column>
                            <el-table-column width='50'>
                                <template slot-scope='scope'>
                    <span class='color-blue pointer' style='text-align: right;'
                          @click='deleteCouponProduct(scope.row.product_id)'>删除</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-form-item>
                <!--商品选择列表 end-->
                <el-form-item label='获取门槛' prop='coupon_obtain_threshold' class='mt-10' v-show='editForm.coupon_type==3'>
                    购物满
                    <el-input v-model='editForm.coupon_obtain_threshold' class='input-middle'></el-input>
                    元 可获得优惠劵
                </el-form-item>
                <el-form-item label='参与用户' class='ml-20' prop='user_type' v-show='editForm.coupon_type!=2'>
                    <el-checkbox-group v-model='user_type'>
                        <el-checkbox :label='1'>普通用户</el-checkbox>
                        <el-checkbox :label='2'>黄金会员</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label='优惠劵备注'>
                    <el-input type='textarea' v-model='editForm.coupon_remark'></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type='primary' @click='editSubmit'>保存</el-button>
                    <el-button @click='$router.back(-1)'>取消</el-button>
                </el-form-item>
            </el-row>
        </el-form>
        <!--编辑表单end -->
    </section>
</template>

<script>
import { editCoupon, getCoupon, getCategoriesList, getProductList } from '../../api/api';

export default {
  data () {
    return {
      fileHeader: {
        Authorization: `Bearer ${this.$store.state.token}`
      },
        Options: [],
        couponProductList: [],
        productList: [],
        classifyProps: {
            value: 'category_id',
            children: 'children',
            label: 'category_name'
        },
        searchName: '',
        listLoading: false,
        editForm: {
        coupon_id: null,
        coupon_title: '',
        coupon_threshold: '',
        coupon_price: '',
        coupon_platform: '1',
        coupon_type: '1',
        coupon_overlay_member: 1,
        start_time: '',
        end_time: '',
        expire_days: '',
        coupon_amount: '',
        coupon_limit: 1,
        coupon_obtain_threshold: '',
        coupon_image: '',
        coupon_remark: '',
        available_product: '1',
        products: [],
        coupon_users: 1,
        is_infinite: ''
      },
      editFormRules: {
        coupon_title: [{ required: true, message: '请优惠劵名称' }],
        coupon_amount: [{ required: true, message: '请输入优惠劵发行量' }],
        coupon_limit: [{ required: true, message: '请输入领取数量限制' }],
        coupon_threshold: [
          { required: true, message: '请输入使用门槛' },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入合法的金额'
          }
        ],
        coupon_price: [
          { required: true, message: '请输入面额' },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入合法的金额'
          }
        ],
        coupon_obtain_threshold: [
          { required: true, message: '请输入购物金额' },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入合法的金额'
          }
        ]
      },
      date: '',
      user_type: [],
      date_type: 1,
      coupon_data: [],
      available_product: 1,
      amount_type: 1
    };
  },
  methods: {
      filterNode(value, data) {
          if (!value) return true;
          return data.label.indexOf(value) !== -1;
      },
      // 获取分类列表
      getClassifyList() {
          this.listLoading = true;
          getCategoriesList().then(res => {
              if (parseInt(res.status) === 1) {
                  this.Options = res.data;
                  this.listLoading = false;
              }
          });
      },
      // 勾选中的分类下商品加入到优惠活动
      getProduct() {
          this.productList = [];
          let nodesList = this.$refs.tree.getCheckedNodes();
          for (let i = 0; i < nodesList.length; i++) {
              if (nodesList[i].products.length !== 0) {
                  for (let j = 0; j < nodesList[i].products.length; j++) {
                      if (this.productList.indexOf(nodesList[i].products[j]) === -1) {
                          // 勾选中商品集合
                          this.productList.push(nodesList[i].products[j]);
                      }
                  }
              }
          }
      },
      // 点击商品分类编辑其下商品
      productView(data) {
          this.productList = [];
          for (let j = 0; j < data.products.length; j++) {
              if (this.productList.indexOf(data.products[j]) === -1) {
                  this.productList.push(data.products[j]);

              }
          }
      },
      deleteProduct(id) {
          for (let i = 0; i < this.productList.length; i++) {
              if (this.productList[i].product_id === id) {
                  this.productList.splice(i, 1);
              }
          }
      },
      // 删除优惠券商品
      deleteCouponProduct(cpid) {
          for (let i = 0; i < this.couponProductList.length; i++) {
              if (this.couponProductList[i].product_id === cpid) {
                  this.couponProductList.splice(i, 1);
              }
          }
      },
      // 商品加入优惠活动
      addToCoupon(){
          for (var i = 0; i < this.productList.length; i++) {
              if (this.couponProductList.indexOf(this.productList[i]) === -1){
                  this.couponProductList.push(this.productList[i]);
              }
          }
      },
      // 行高亮
      tableRowClassName({row, rowIndex}, i) {
          if (rowIndex === i) {
              return 'success-row';
          }
      },
      searchProductList() {
          let list = [];
          for (let i = 0; i < this.productList.length; i++) {
              if (
                  this.productList[i].product_name
                      .toLowerCase()
                      .indexOf(this.searchName.toLowerCase()) >= 0
              ) {
                  list.push(this.productList[i]);
              }
          }
          this.productList = list;
      },
    // 编辑
    editSubmit () {
      this.editFormRules.coupon_obtain_threshold[0].required =
        this.editForm.coupon_type === '3' ? 1 : 0;
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          if (this.editForm.available_product === 0) {
              for (var i = 0; i < this.couponProductList.length; i++) {
                      this.editForm.products.push(this.couponProductList[i].product_id);
              }
              // this.editForm.products = this.couponProductList;
              console.log("指定商品集合"+ this.editForm.products)
          }
          if (this.date_type === 1) {
            this.editForm.start_time = this.date[0];
            this.editForm.end_time = this.date[1];
            this.editForm.expire_days = '';
          } else {
            this.editForm.start_time = '';
            this.editForm.end_time = '';
          }
          if (this.amount_type === 2) {
            this.editForm.coupon_amount = '';
            this.editForm.is_infinite = 1;
          }
          // 处理参与用户数据
          this.editForm.coupon_users =
            this.user_type.length === 2 ? '3' : this.user_type[0];

          editCoupon(this.editForm).then(res => {
            if (parseInt(res.status) === 1) {
              this.$message({
                message: '提交成功',
                type: 'success'
              });
            } else {
              this.$alert('编辑失败', '失败', { type: 'error' });
            }
          });
        }
      });
    },
    getOne () {
      getCoupon(this.$route.params.id).then(res => {
        if (res.data.coupon_overlay_member === '1') {
          this.coupon_overlay_member = 1;
        } else {
          this.coupon_overlay_member = 0;
        }
        if (res.data.start_time === null) {
          this.date_type = 2;
        } else {
          this.date = [res.data.start_time, res.data.end_time];
        }
        res.data.coupon_overlay_member = 1;
        if (res.data.coupon_type !== 2) {
          this.user_type =
            res.data.coupon_users === '1'
              ? [1]
              : res.data.coupon_users === '2' ? [2] : [1, 2];
        }
        this.editForm = Object.assign({}, res.data);
        this.editForm.available_product = parseInt(res.data.available_product);
        this.couponProductList = this.editForm.products
        this.editForm.products=[];
      });
    }
  },
  mounted () {
    this.getOne();
    this.getClassifyList();
  }
};
</script>
<style rel='stylesheet/sass' lang='sass' scoped>
    $inputWidth: 300px
    .upload-success
        text-align: center
        vertical-align: middle
        div
            display: inline-block
            width: 100px

    .form-title
        margin: 20px 0
        padding-bottom: 5px
        font-size: 18px
        border-bottom: 1px solid #DFE4ED

    .button-div
        padding-bottom: 200px
        text-align: right
        margin-top: 30px
        button
            width: 100px
            margin-left: 20px

    .row-padding
        padding: 0 20px 20px 80px

    hr
        border-style: dashed
        border-color: #DFE4ED

    .input-middle
        width: $inputWidth

    .mt-10
        margin-top: 10px

    .mb-20
        margin-bottom: 20px

    .center
        text-align: center
</style>
<style>
    /*去掉头部*/
    #tableCssOne .el-table__header-wrapper {
        display: none !important;
    }

    #tableCssTwo .el-table__header-wrapper {
        display: none !important;
    }

    .transfer-footer {
        margin-left: 20px;
        padding: 6px 5px;
    }

    .search {
        width: 98%;
        position: absolute;
        top: 8px;
        right: 2px;
        z-index: 9;
    }

    .el-table__header-wrapper {
        height: 40px;
    }
</style>